package com.kevin.Code.Tree;

/**
 * @author Vinlee Xiao
 * @Classname KthSmallestElementinabst
 * @Description Leetcode 230. 二叉搜索树中第K小的元素 中等难度
 * @Date 2021/12/29 11:13
 * @Version 1.0
 */
public class KthSmallestElementinabst {

    int index = 0;
    int result = 0;

    /**
     * 中序遍历的顺序
     *
     * @param root
     * @param k
     * @return
     */
    public int kthSmallest(TreeNode root, int k) {
        dfs(root, k);
        return result;
    }

    /**
     * 中序遍历
     *
     * @param root
     * @param k
     * @return
     */
    private void dfs(TreeNode root, int k) {

        if (root == null) {
            return;
        }
        dfs(root.left, k);
        index++;
        if (k == index) {
            result = root.val;
            return;
        }
        dfs(root.right, k);
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(1);
        TreeNode node3 = new TreeNode(4);
        TreeNode node4 = new TreeNode(2);

        node1.left = node2;
        node1.right = node3;
        node2.right = node4;
        KthSmallestElementinabst kthSmallestElementinabst = new KthSmallestElementinabst();
        int i = kthSmallestElementinabst.kthSmallest(node1, 1);
        System.out.println(i);
    }

}
